import {saveWebLocation} from '../../bomb/db.location.js'
import {setCookie} from "../../utils/cookie.js";

window._AMapSecurityConfig = {
    securityJsCode: '5c2c03177c4918272773622a962ed977',
}

const apiKey = 'f0905613f3af1fa969c4eaecf0bae0d2'
let mapApi = "https://webapi.amap.com/maps?v=2.0&key=" + apiKey;
$.getScript(mapApi).done(() => {
    // amap的js文件加载完成后，开始定位
    getLocation();
})

// 定位成功回调接口
function saveLocationResult(res) {
    setCookie("location.city", res.city | "")
    setCookie("location.district", res.district || "")
    // 更新天气
    if (window.updateWeather) {
        window.updateWeather({
            city: res.city,
            district: res.district
        })
    }
    saveWebLocation(res)
}

function getLocationAddress(lng, lat) {
    AMap.plugin('AMap.Geocoder', function () {
        const location = {}
        location.lng = lng;
        location.lat = lat

        var geocoder = new AMap.Geocoder({})
        geocoder.getAddress([lng, lat], function (status, result) {
            console.log(result)
            if (status === 'complete' && result.info === 'OK') {
                let addressComponent = result.regeocode.addressComponent;
                location.province = addressComponent.province
                location.city = addressComponent.city
                location.district = addressComponent.district
                location.street = addressComponent.street
                location.streetNumber = addressComponent.streetNumber
                location.township = addressComponent.township
                location.address = result.regeocode.formattedAddress

                // 调用定位成功回调接口
                saveLocationResult(location)
            } else {
                location.error = JSON.stringify(result)
                saveLocationResult(location)
            }
        })
    })
}


function getLocation() {
    AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 30 * 1000
        })

        console.log("Amap开始定位")
        geolocation.getCurrentPosition(function (status, result) {
            if (status === 'complete') {
                onComplete(result)
            } else {
                result.status = status
                onError(result)
            }
        });

        function onComplete(data) {
            // data是具体的定位信息
            console.log(data)
            // 根据经纬度获取位置详情
            getLocationAddress(data.position.lng, data.position.lat)
        }

        function onError(data) {
            // 定位出错
            console.error(data)
            saveWebLocation({error: JSON.stringify(data)})
        }
    })
}


